/*
https://leetcode.cn/problems/checking-existence-of-edge-length-limited-paths/solutions/2018397/jian-cha-bian-chang-du-xian-zhi-de-lu-ji-cdr5/
 */
import java.util.Arrays;
import java.util.Comparator;

public class Solution1697 {

    static class Bing{
        int[] b;
        public Bing(int n){
            b=new int[n];
            for (int i=0;i<n;i++){
                b[i]=i;
            }
        }

        public void union(int x,int y){
            int xx=find(x),yy=find(y);
            if (xx!=yy){
                b[xx]=yy;
            }
        }

        public int find(int x){
            return b[x]==x?x:(b[x]=find(b[x]));
        }
    }

    public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {
        int[][] newQuery=new int[queries.length][4];
        for (int i=0;i<newQuery.length;i++){
            newQuery[i][0]=queries[i][0];
            newQuery[i][1]=queries[i][1];
            newQuery[i][2]=queries[i][2];
            newQuery[i][3]=i;
        }
        boolean[] ans=new boolean[queries.length];
        Bing bing=new Bing(n);
        Arrays.sort(edgeList, Comparator.comparingInt(a -> a[2]));
        Arrays.sort(newQuery, Comparator.comparingInt(a -> a[2]));
        int t=0;
        for (int[] query : newQuery) {
            while (t<edgeList.length && edgeList[t][2]<query[2]){
                bing.union(edgeList[t][0],edgeList[t][1]);
                t++;
            }
            ans[query[3]]=bing.find(query[0])==bing.find(query[1]);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution1697().distanceLimitedPathsExist(3, new int[][]{{0, 1, 2}, {1, 2, 4}, {2, 0, 8}, {1, 0, 16}}, new int[][]{{0, 1, 2}, {0, 2, 5}})));
    }
}
